package org.glut.saltedfish.service;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.glut.saltedfish.domain.User;
import org.glut.saltedfish.mapper.UserMapper;
import org.glut.saltedfish.utils.MybatisUtil;

public class UserServiceImpl {
    private static final Logger logger = Logger.getLogger(UserServiceImpl.class);  // 改成log4j 1.x的获取Logger方式

    /**
     *
     * @param user
     * @return boolean
     */
    public static boolean login(User user) {
        try (SqlSession session = MybatisUtil.getSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            return mapper.queryLogin(user) != null;
        }
    }

    public static User getUserByPhone(String phone) {
        try (SqlSession session = MybatisUtil.getSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            return mapper.getUserByPhone(phone);
        }
    }

    /**
     * 用户注册方法。
     *
     * @param user 待注册的用户对象，包含手机号、邮箱等信息
     * @return 注册成功返回 true；如果手机号或邮箱已存在，则返回 false
     */
    public boolean registerUser(User user) {
        try (SqlSession session = MybatisUtil.getSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            int count = mapper.checkExists(user.getUsername(),user.getPhone(), user.getEmail());
            logger.debug("检查用户名/手机号/邮箱是否存在: " + count);
            if (count > 0) {
                logger.debug("用户名或手机号或邮箱已存在，注册失败");
                return false;
            }
            mapper.insertUser(user);
            session.commit();
            logger.debug("用户注册成功: " + user);
            return true;
        } catch (Exception e) {
            logger.error("用户注册失败", e);
            return false;
        }
    }

}
